What are Promises in JavaScript and how do they work?
What are Promises in JavaScript and how do they work?
188
18-Jun-2024
Updated on 19-Jun-2024
Ravi Vishwakarma
18-Jun-2024A promise is an asynchronous action that may be completed at some point in the future and produce a value. This value is not necessarily known at the time of its creation. Once the value is produced, it notifies the user.
Promises provide a robust way to wrap the result of asynchronous work, overcoming the problem of deeply nested callbacks.
The Promise object takes a callback function as a parameter, which, in turn, takes two parameters, resolve and reject. The promise is either fulfilled or rejected.
Here's an in-depth look at what Promises are and how they work:
Basics of Promise
A promise created using the
promise
constructor in JavaScript.States
A Promise has three states:
Working with Promises
Chaining with
.then()
Once a Promise is fulfilled or rejected, you can handle the result or error using
.then()
and.catch()
:You can add multiple
.then()
methods to handle a sequence of asynchronous operations:Using
.finally()
The
.finally()
method is used to execute a callback once the Promise is settled (fulfilled or rejected):Summary
.then()
for handling fulfilled results,.catch()
for handling errors, and.finally()
for cleanup actions.Promise.all()
andPromise.race()
help in combining multiple Promises.async
andawait
provide a more synchronous-like way to handle asynchronous code.Example: Fetch Data from an API using Promises
Explanation:
fetch('https://jsonplaceholder.typicode.com/posts/1')
: Initiates a network request to the specified URL.fetch
returns a Promise that resolves to theResponse
object representing the response to the request..then(response => {...})
: The first.then()
method processes theResponse
object. Theresponse.ok
property checks if the response status is in the range 200-299, indicating a successful request.return response.json();
: If the response is okay, we callresponse.json()
to parse the JSON body text from the response. This returns a Promise that resolves to the parsed JSON data..then(data => {...})
: The second.then()
method processes the parsed JSON data. Here, we can handle the data, such as logging it to the console..catch(error => {...})
: The.catch()
method handles any errors that occur during the fetch operation or while processing the response. This includes network errors and the errors thrown if the response is not ok.Read also,
Implementation of Data Structures in JavaScript
Explain the concept and use DOM Manipulation